export default class Canvas {
    constructor () {
        this.startColor = null
        this.stopColor = null
        this.color = null
    }

    setStartColor (color) {
        this.startColor = color
    }

    setStopColor (color) {
        this.stopColor = color
    }

    setColor (color) {
        this.color = color
    }

    getClientHeight () {
        return document.documentElement.clientHeight || document.body.clientHeight
    }

    getClientWidth () {
        return document.documentElement.clientWidth || document.body.clientWidth
    }

    getCanvas () {
        const canvas = document.createElement('canvas')
        canvas.height = this.getClientHeight()
        canvas.width = this.getClientWidth()
        return canvas
    }

    getContext (canvas) {
        if (!canvas.getContext) {
            throw new Error('浏览器不支持canvas')
        }
        return canvas.getContext('2d')
    }

    random (min, max) {
        return Math.round(Math.random() * (max - min) + min)
    }

    drawBgColor (ctx) {
        const width = this.getClientWidth()
        const height = this.getClientHeight()
        const linearGradient = ctx.createLinearGradient(width / 2, 0, width / 2, height)
        linearGradient.addColorStop(0, this.startColor)
        linearGradient.addColorStop(1, this.stopColor)
        ctx.fillStyle = linearGradient
        ctx.fillRect(0, 0, width, height)
        ctx.save()
    }

    drawRandom (ctx) {
        const fontSize = this.random(48, 100)
        const word = this.random(0, 9)
        const x = this.random(0, this.getClientHeight() * 1.5)
        const y = this.random(0, this.getClientHeight() * 1.5)
        const rad = Math.PI / this.random(1, 4)
        ctx.fillStyle = this.color
        ctx.font = fontSize + 'px serif'
        ctx.rotate(rad)
        ctx.fillText(word, x, y)
        ctx.restore()
    }

    toImageURL (startColor, stopColor, color) {
        const canvas = this.getCanvas()
        const ctx = this.getContext(canvas)
        const count = this.random(200, 300)
        this.setStartColor(startColor)
        this.setStopColor(stopColor)
        this.setColor(color)
        this.drawBgColor(ctx)
        for (let i = 0; i < count; i++) {
            this.drawRandom(ctx)
        }
        return canvas.toDataURL('image/png')
    }
}
